#find rects
import  sensor, image, lcd, time

lcd.init()
sensor.reset()
sensor.set_contrast(1)
sensor.set_gainceiling(16)
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.run(1)
sensor.skip_frames(30)
tim = time.ticks_ms()
b=[75,35,170,170]
rectangle_coordinate_show=[]
def find_four_points(img,b):
    rectangle_coordinate=[]
    for r in img.find_rects(threshold = 18000,roi=b):
        img.draw_rectangle(r.rect(), color = (255, 0, 0))
        for p in r.corners():
#             img.draw_circle(p[0], p[1], 5, color = (0, 255, 0))
            rectangle_coordinate.append([p[0], p[1]])
    img.draw_rectangle(b)
    return rectangle_coordinate

def show_four_circle(r):
    for p in r:
        img.draw_circle(p[0], p[1], 5, color = (0, 255, 0))

def calculate_area(point1, point2, point3, point4):
    # 计算向量AB和向量AC的叉积
    def cross_product(vector1, vector2):
        return vector1[0] * vector2[1] - vector1[1] * vector2[0]
    # 计算三角形的面积
    def triangle_area(point1, point2, point3):
        vector1 = (point2[0] - point1[0], point2[1] - point1[1])
        vector2 = (point3[0] - point1[0], point3[1] - point1[1])
        return 0.5 * abs(cross_product(vector1, vector2))
    # 计算四边形的面积
    area = triangle_area(point1, point2, point3) + triangle_area(point1, point3, point4)
    return area

while True:
    img = sensor.snapshot()
    if rectangle_coordinate_show==[]:
        rectangle_coordinate=find_four_points(img,b)#[[92, 164], [232, 159], [227, 63], [89, 68]]
    try:
        area=calculate_area(rectangle_coordinate[0], rectangle_coordinate[1], rectangle_coordinate[2], rectangle_coordinate[3])
        print(area)
        if  area>5000 and area<7000:
            rectangle_coordinate_show=rectangle_coordinate
            show_four_circle(rectangle_coordinate_show)
    except:
        pass



